<?php

/* Simulation recorder
 * 
 * Anas 
 * 
 * Jul 2013
 * 
 * creates a dump file given the SimuRec data from frontend
 * 
 * The dump created is in xdotool format
 */


$dump_path = './dumps/';

$dump_file = $dump_path.substr(md5(time()), 0, 5).'_xdotool'.date("Y-m-d_H-i-s").'.dump';

if( !file_exists($dump_path) ) {
    mkdir($dump_path, 0777);
    chmod($dump_path, 0777);
}

$browser_name = 'Mozilla Firefox';

$dump_data = convertRecToXdotoolDump($_POST['rec'], $browser_name);

if( $dump_data ) {
            
    $res = file_put_contents($dump_file, $dump_data);
    
    if( $res === FALSE ) {
        throw new Exception('Failed writing dump file - '.$dump_file);
    }
}


/**
 * Converts the user data to xdotool simulation data
 */
function convertRecToXdotoolDump($rec, $browser_name)
{      
    //initialize dump
    $dump = '
WID=`xdotool search --name "'.$browser_name.'" | head -1`
xdotool windowactivate $WID
xdotool windowsize --usehints $WID 100% 100%

    ';
    
    $lines = explode("\n", $rec);
        
    $last_line = '';
    
    $prefix = 'xdotool';
    
    foreach( $lines as $line ) {                                
        
        //get the last typed event data saved
        if( strpos($line, "type ") !== FALSE ) {
            $last_line = $line;                                    
            continue;
        }
        
        if( $last_line !== '' ) {
            $dump .= $prefix.' '.$last_line."\n";
            $dump .= $prefix.' sleep 1'."\n";
        }
        
        $dump .= $prefix.' '.$line."\n";
        $dump .= $prefix.' sleep 1'."\n";
        
        $last_line = '';
    }
    
    $dump .= $prefix." sleep 10";
    $dump .= "\n\n";
    
    return $dump;
}

?>
